<template>
    <div class="chatBox-container">
      <div class="chatBox-header" v-if="sessionId !== ''" :style="[{'text-indent': getProportionHeight(0.04) + 'px'}]">
        <span :style="[{'line-height': getProportionHeight(0.09) + 'px'}, {'font-size': getProportionHeight(0.023) + 'px'}]">{{displayName}}</span>
      </div>
      <div class="chatBox-content" v-if="sessionId !== ''" :style="[{'padding-right': getProportionHeight(0.02) + 'px'}, {'padding-left': getProportionHeight(0.02) + 'px'}]">
        <div v-for="(message, i) in messageList">
          <div class="message-time" v-if="showMessageTime(i)">
            <span class="message-time-text">
              &nbsp;{{showMessageTimeText(message.time)}}&nbsp;
            </span>
          </div>
          <div v-if="message.fromUserId === userId">
            <div class="chatBox-content-right">
              <el-row style="display:block">
                <el-col :span="8">
                  <hr style="border: 1px solid transparent; width: 1px">
                </el-col>
                <el-col :span="14">
                  <div class="chatBox-content-right-name"
                       :style="[{'line-height': getProportionHeight(0.04) + 'px'}, {'font-size': getProportionHeight(0.016) + 'px'}]">
                    {{message.fromUserName}}
                  </div>
                  <br>
                  <br>
                  <div class="chatBox-content-right-message">
                    <div class="message-right">
                      {{message.content}}
                    </div>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div class="avatar" :style="setDynamicHeight(0.09)">
                    <el-avatar class="avatarImg"  shape="square" :size="getProportionHeight(0.05)" :src="config.baseConfig.photoBaseUrl +message.fromUserAvatarUrl"></el-avatar>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
          <div v-else-if="message.fromUserId === 'system'">
            <div class="chatBox-content-system">
              <el-row>
                <el-col :span="2">
                  <hr style="border: 1px solid transparent">
                </el-col>
                <el-col :span="20">
                  <el-divider style="background-color:rgba(255,255,255,0.15)">
                    <span>{{message.content}}</span>
                  </el-divider>
                </el-col>
                <el-col :span="2">
                  &nbsp;
                </el-col>
              </el-row>
            </div>
          </div>
          <div v-else>
            <div class="chatBox-content-left">
              <el-row>
                <el-col :span="2">
                  <div class="avatar" :style="setDynamicHeight(0.09)">
                    <el-avatar class="avatarImg"  shape="square" :size="getProportionHeight(0.05)" :src="config.baseConfig.photoBaseUrl +message.fromUserAvatarUrl"></el-avatar>
                  </div>
                </el-col>
                <el-col :span="14">
                  <div class="chatBox-content-left-name" :style="[{'line-height': getProportionHeight(0.04) + 'px'}, {'font-size': getProportionHeight(0.016) + 'px'}]">
                    {{message.fromUserName}}
                  </div>
                  <div class="chatBox-content-left-message">
                    <div class="message-left">
                      {{message.content}}
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
        <span id="chatBox-content-bottom"></span>
      </div>
      <div class="chatBox-send" v-if="sessionId !== ''">
        <div class="chatBox-send-tools">
          <el-row>
            <el-col :span="1"><hr style="border: 1px solid transparent"></el-col>
            <el-col :span="2">
              <i class="el-icon-folder" :style="[{'line-height': getProportionHeight(0.043) + 'px'}, {'font-size': getProportionHeight(0.03) + 'px'}]"></i>
            </el-col>
            <el-col :span="2">
              <i class="el-icon-chat-dot-round" :style="[{'line-height': getProportionHeight(0.043) + 'px'}, {'font-size': getProportionHeight(0.03) + 'px'}]"></i>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-form ref="form" :model="messageForm">
            <div class="chatBox-send-content">
              <el-input
                v-model="messageForm.messageContent"
                maxlength="160"
                type="textarea"
                :rows="2">
              </el-input>
            </div>
            <div class="chatBox-send-button" :style="[{'line-height': getProportionHeight(0.025) + 'px'}, {'font-size': getProportionHeight(0.03) + 'px'}]">
              <el-row>
                <el-col :span="19">
                  <hr :style="[{'border': '1px solid transparent'}, {'width': getProportionWidth(0.02) + 'px'}]">
                </el-col>
                <el-col :span="5">
              <span>
                <el-button size="mini" :style="[{'width': getProportionWidth(0.042) + 'px'}, {'height': getProportionHeight(0.035) + 'px'}]" @click="sendTextMessage">发送</el-button>
              </span>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>
      </div>
    </div>
</template>
<script>
  import moment from 'moment'
  export default {
    name: "chatBox",
    props: {
      avatarUrl: {
        type: String
      },
      userName: {
        type: String
      },
      pubSessionIdVue: {
        type: Object
      },
      sendMessage: {
        type: Function,
        default: null,
      }
    },
    data () {
      return {
        displayName: "",
        userId: "",
        messageList: [],
        messageForm: {
          messageContent: ""
        },
        sessionId: ""
      }
    },
    beforeDestroy () {
      document.removeEventListener('scroll', this.handleScroll,true);
    },
    mounted() {
      document.addEventListener('scroll', this.handleScroll,true);
      this.pubSessionIdVue.$on('CHANGE_SESSION_ID', data => {
        this.getSessionName(data);
        this.getMessage(data);
      });
      // 初始化
      this.init()
    },
    methods: {
      handleScroll(e){
        if (0 === e.target.scrollTop) {
          this.getNewMessage();
        }
      },
      init() {
        this.userId = this.$cookieStore.getCookie("userId");
      },
      async getNewMessage() {
        if (0 !== this.messageList) {
          const message = this.messageList[0];
          if (message.time) {
            const paramObj = {};
            paramObj.sessionId = this.sessionId;
            paramObj.time = new Date(message.time).getTime();
            const result = await this.$api.message.getMessage(paramObj);
            if (result.code === 0){
              if (result.data.length > 0) {
                this.messageList = [].concat(result.data).concat(this.messageList);
              } else {
                const messageTop = {};
                messageTop.fromUserId = "system";
                messageTop.fromUserName = "system";
                messageTop.type = 1;
                messageTop.content = '已经到顶了';
                const arrTemp = [];
                arrTemp.push(messageTop);
                this.messageList = arrTemp.concat(this.messageList);
              }
            } else {
              this.$message.error(result.msg);
            }
          }
        }
      },
      async getSessionName(sessionId) {
        this.sessionId = sessionId;
        const paramObj = {};
        paramObj.userId = this.userId;
        paramObj.sessionId = sessionId;
        const result = await this.$api.message.getSessionInfo(paramObj);
        if (result.code === 0) {
          this.displayName = result.data.displayName;
        } else {
          this.$message.error(result.msg);
        }
      },
      async getMessage(sessionId) {
        const paramObj = {};
        paramObj.sessionId = sessionId;
        const result = await this.$api.message.getMessage(paramObj);
        if (result.code === 0) {
          this.messageList = result.data;
          this.jumpToBottom();
        } else {
          this.$message.error(result.msg);
        }
      },
      jumpToBottom() {
        const timer = setTimeout(()=>{
          document.getElementById("chatBox-content-bottom").scrollIntoView();
        },50);
      },
      sendTextMessage() {
        if (this.sessionId !== '' && this.messageForm.messageContent !== '') {
          const message = {};
          message.sessionId = this.sessionId;
          message.fromUserId = this.userId;
          message.type = 1;
          message.content = this.messageForm.messageContent;
          this.sendMessage(message);
          this.addMessage(message);
        }
      },
      addMessage(message) {
        const messageVo = {};
        messageVo.messageId = '';
        messageVo.sessionId = this.sessionId;
        messageVo.fromUserId = this.userId;
        messageVo.fromUserName = this.userName;
        messageVo.fromUserAvatarUrl = this.avatarUrl;
        messageVo.type = message.type;
        messageVo.content = message.content;
        messageVo.time = new Date();
        this.messageForm.messageContent = '';
        this.addMessageAndJump(messageVo);
      },
      addMessageAndJump(message){
        this.messageList.push(message);
        this.jumpToBottom();
      },
      showMessageTime(i) {
        if (i > 0) {
          const topMessage = this.messageList[i - 1];
          const bottomMessage = this.messageList[i];
          if (topMessage.time && bottomMessage.time
            && (new Date(bottomMessage.time).getTime() - new Date(topMessage.time).getTime()) > 10 * 60 * 1000) {
            return true;
          }
        }
        return false;
      },
      showMessageTimeText(time) {
        if (time) {
          const messageDate = new Date(time);
          if (moment(messageDate).format('YYYY-MM-DD') === moment(new Date()).format('YYYY-MM-DD')) {
            return moment(messageDate).format('HH:mm');
          } else {
            return moment(messageDate).format('YY/MM/DD HH:mm:ss');
          }
        }
      }
    }
  }
</script>

<style scoped>
  .chatBox-container{
    height: 100%;
    background-color: #ffffff;
    border-top-right-radius: 2px;
    border-bottom-right-radius: 2px;
  }
  .chatBox-header{
    height: 10%;
    color: #000000;
    background-color: #F5F5F5;
    border-bottom-style: solid;
    border-width: 1px;
    border-color: #E7E7E7;
    border-top-right-radius: 2px;
  }
  .message-time{
    width: 100%;
    text-align: center;
  }
  .message-time-text{
    background: #DADADA;
    font-size: 12px;
    border-radius: 2px;
  }
  .chatBox-content{
    overflow: auto;
    height: 70%;
    background-color: #F5F5F5;
    border-bottom-style: solid;
    border-width: 1px;
    border-color: #E7E7E7;
  }
  .chatBox-send{
    height: 20%;
    background-color: rgba(255,255,255,0);
  }
  .chatBox-send-tools{
    height: 10%;
    color: #565656;
  }
  .chatBox-send-content{
    height: 60%;
  }
  .chatBox-send-button{
    height: 30%;
  }
  .chatBox-send-content >>>.el-textarea__inner {
    padding: 0 25px;
  }
  .chatBox-send-content>>>.el-textarea__inner {
    border: 0;
    resize: none;
  }
  .chatBox-content-left{
    width: 100%;
  }
  .chatBox-content-right{
    width: 100%;
  }
  .chatBox-content-system{

  }
  .chatBox-content-system >>>.el-divider__text{
    background-color: #F5F5F5;
    color: #969696;
  }
  .chatBox-content-left-name{
    color: #969696;
  }
  .chatBox-content-right-name{
    float:right;
    color: #969696;
  }
  .chatBox-content-left-message {
    margin-left: 6px;
  }
  .chatBox-content-right-message {
    margin-right: 6px;
  }
  .avatar {
    height: 100%;
    width: 100%;
    position: relative;
  }
  .avatarImg{
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
  }
  .message-left {
    float:left;
    background-color: #ffffff;
    border: 1px solid #E7E7E7;
    color: #000000;
    font-size: 12px;
    line-height: 18px;
    padding: 5px 12px 5px 12px;
    box-sizing: border-box;
    border-radius: 2px;
    position: relative;
    word-break: break-all;
  }
  /** 通过对小正方形旋转45度解决 **/
  .message-left::before {
    content: '';
    position: absolute;
    top: 12px;
    left: -3px;
    width: 4px;
    height: 4px;
    margin-top: -6px;
    background: inherit;
    transform: rotate(45deg);
    border-left-style:solid;
    border-left-color:#E7E7E7;
    border-left-width: 1px;
    border-bottom-style:solid;
    border-bottom-color:#E7E7E7;
    border-bottom-width: 1px;
  }
  .message-right {
    float:right;
    top: -10px;
    background-color: #9EF36A;
    border: 1px solid #E7E7E7;
    color: #000000;
    font-size: 12px;
    line-height: 18px;
    padding: 5px 12px 5px 12px;
    box-sizing: border-box;
    border-radius: 2px;
    position: relative;
    word-break: break-all;
  }
  /** 通过对小正方形旋转45度解决 **/
  .message-right::before {
    float:right;
    content: '';
    position: absolute;
    top: 12px;
    right: -3px;
    width: 4px;
    height: 4px;
    margin-top: -6px;
    background: inherit;
    /*自动继承父元素的背景*/
    transform: rotate(45deg);
    border-right-style:solid;
    border-right-color:#E7E7E7;
    border-right-width: 1px;
    border-top-style:solid;
    border-top-color:#E7E7E7;
    border-top-width: 1px;
  }
  /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
  /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
  ::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    background-color: #F5F5F5;
  }
  /*定义滚动条轨道 内阴影+圆角*/
  ::-webkit-scrollbar-track {
    background-color: #EBE8E7;
  }
  /*定义滑块 内阴影+圆角*/
  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #B4B1B0
  }
</style>
